﻿@{
    ViewBag.PageTitle = "编辑稿件 - " + ViewBag.site.SeoTitle;
    ViewBag.PageKeyword = ViewBag.site.SeoKeyword;
    ViewBag.PageDescription = ViewBag.site.SeoDescription;
}
<!--quill editer-->
<link rel="stylesheet" href="~/lib/quill/quill.core.css" />
<link rel="stylesheet" href="~/lib/quill/quill.snow.css" />
<link rel="stylesheet" href="~/lib/quill/quill.bubble.css" />
<link rel="stylesheet" href="~/lib/quill/quill-zh-cn.css" />
<div class="wrapper">
    <div class="account-box">
        @{
            await Html.RenderPartialAsync("_AccountNav", "contribute");
        }
        <div class="right-box">
            <div class="tab-box">
                <div class="menu-box">
                    <div class="item-box active">
                        <span>我的投稿</span>
                    </div>
                </div>
                <div class="btn-box">
                    <el-link :underline="false" icon="el-icon-arrow-left" href="/account/contribute/list">返回</el-link>
                </div>
            </div>
            <div class="content">
                <el-form ref="editForm" :model="model" :rules="rules" label-position="right" label-width="120px">
                    <el-form-item prop="title" label="标题">
                        <el-input v-model="model.title" placeholder="必填，文章标题"></el-input>
                    </el-form-item>
                    <el-form-item prop="source" label="来源">
                        <el-input v-model="model.source" placeholder="选填，文章来源"></el-input>
                    </el-form-item>
                    <el-form-item prop="author" label="作者">
                        <el-input v-model="model.author" placeholder="选填，文章作者"></el-input>
                    </el-form-item>
                    <el-form-item prop="imgUrl" label="封面图片">
                        <dt-upload-text v-model="model.imgUrl"
                                        placeholder="请上传封面图片"
                                        width="20%"
                                        height="10%"
                                        fit="contain"
                                        :size="sysconfig.imgSize"
                                        exts="jpg,jpeg,png,gif"
                                        action="/upload">
                        </dt-upload-text>
                    </el-form-item>
                    <el-form-item prop="content" label="内容">
                        <dt-editor v-model="model.content" placeholder="请输入内容介绍"></dt-editor>
                    </el-form-item>
                    <el-form-item prop="channelId" label="频道">
                        <el-select v-model="model.channelId" clearable placeholder="请选择频道" @@change="handleChannelChange">
                            <el-option v-for="item in channelList"
                                       :key="item.id"
                                       :label="item.title"
                                       :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="channelModel.isAlbum==1" label="相册">
                        <dt-upload-album v-model="form.albumList"></dt-upload-album>
                    </el-form-item>
                    <el-form-item v-show="channelModel.isAttach==1" label="附件上传">
                        <dt-upload-attach v-model="form.attachList" :size="sysconfig.attachSize" :exts="sysconfig.fileExtension"></dt-upload-attach>
                    </el-form-item>
                    <template v-if="model.fields.length>0">
                        <template v-for="(field,index) in model.fields">
                            <!--单行文本框-->
                            <el-form-item v-if="field.controlType=='input'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <el-input v-if="field.isPassword==0" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
                                <el-input v-else v-model="field.fieldValue" :placeholder="field.validTipMsg" show-password></el-input>
                            </el-form-item>
                            <!--多行文本框-->
                            <el-form-item v-else-if="field.controlType=='textarea'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <el-input type="textarea" v-model="field.fieldValue" :placeholder="field.validTipMsg"></el-input>
                            </el-form-item>
                            <!--编辑器-->
                            <el-form-item v-else-if="field.controlType=='editor'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <div style="min-height:230px;">
                                    <dt-editor v-if="field.editorType==0" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
                                    <dt-editor mini v-if="field.editorType==1" v-model="field.fieldValue" placeholder="field.validTipMsg"></dt-editor>
                                </div>
                            </el-form-item>
                            <!--图片上传-->
                            <el-form-item v-else-if="field.controlType=='images'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <dt-upload-text v-model="field.fieldValue"
                                                :placeholder="field.validTipMsg"
                                                exts="jpg,jpeg,png,gif"
                                                :size="sysconfig.imgSize"
                                                action="/upload">
                                </dt-upload-text>
                            </el-form-item>
                            <!--视频上传-->
                            <el-form-item v-else-if="field.controlType=='video'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <dt-upload-text v-model="field.fieldValue"
                                                :placeholder="field.validTipMsg"
                                                :exts="sysconfig.videoExtension"
                                                :size="sysconfig.videoSize"
                                                action="/upload"></dt-upload-text>
                            </el-form-item>
                            <!--日期时间-->
                            <el-form-item v-else-if="field.controlType=='datetime'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <el-date-picker v-model="field.fieldValue" value-format="yyyy-MM-dd hh:mm:ss" :placeholder="field.validTipMsg" type="datetime">
                                </el-date-picker>
                            </el-form-item>
                            <!--多项单选-->
                            <el-form-item v-else-if="field.controlType=='radio'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <el-radio-group v-model="field.fieldValue">
                                    <el-radio v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <!--多项多选-->
                            <el-form-item v-else-if="field.controlType=='checkbox'" :prop="'fields.'+index+'.fieldValue'" :rules="fieldRules[field.name]" :label="field.title">
                                <el-checkbox-group v-model="field.fieldValue">
                                    <el-checkbox v-for="(item,index) in field.options" :label="item[1]" :key="item[1]">{{item[0]}}</el-checkbox>
                                </el-checkbox-group>
                            </el-form-item>
                        </template>
                    </template>
                    <el-form-item>
                        <el-button type="primary" :disabled="model.status==1" @@click="submitForm">确认提交</el-button>
                        <el-button @@click="common.back(-1)">取消</el-button>
                    </el-form-item>
                </el-form>

            </div>
        </div>
    </div>
</div>

@section Scripts{
    @*<script src="~/lib/babel-polyfill/polyfill.min.js"></script>*@
    <script src="~/js/upload.component.js"></script>
    <!--quill editer-->
    <script src="~/lib/quill/quill.min.js"></script>
    <script src="~/lib/quill/vue-quill-editor.js"></script>
    <script src="~/lib/quill/image-resize.min.js"></script>
    <script src="~/js/editor.component.js"></script>

    <script>
        //初始化VUE
        var ve = new Vue({
            el: '#app',
            data: {
                account: {}, //账户信息
                channelList: [],
                channelModel: {},
                fieldRules: {},
                sysconfig: {},
                form: {
                    albumList: [],//相册列表,保存取值
                    attachList: [],
                },
                model: {
                    id: 0,
                    channelId: '',
                    title: '',
                    source: '',
                    author: '',
                    imgUrl: '',
                    fieldMeta: '',
                    albumMeta: '',
                    attachMeta:'',
                    content: '',
                    userId: 0,
                    userName: '',
                    addTime: '',
                    updateBy: '',
                    updateTime: '',
                    status: 0,
                    fields: [],
                    albums: [],
                    attachs: [],
                },
                rules: {
                    title: [
                        { required: true, message: '请输入文章标题', trigger: 'blur' }
                    ],
                    source: [
                        { max: 128, message: '来源不可超出128字符', trigger: 'blur' }
                    ],
                    author: [
                        { max: 128, message: '作者不可超出128字符', trigger: 'blur' }
                    ],
                    imgUrl: [
                        { max: 512, message: '图片地址不可超出512字符', trigger: 'blur' }
                    ],
                    content: [
                        { required: true, message: '投稿内容不能为空', trigger: 'blur' },
                    ],
                    channelId: [
                        { required: true, message: '请选择投稿频道', trigger: 'change' }
                    ],
                }
            },
            methods: {
                //初始化数据
                async initData(id) {
                    let _this = this;

                    //获取会员信息
                    await AxiosAjax({
                        url: `/account/member`,
                        success: function (res) {
                            _this.account = res.data;
                        }
                    });
                    //会员信息
                    await AxiosAjax({
                        url: `/client/setting/uploadconfig`,
                        loading: false,
                        success: function (res) {
                            _this.sysconfig = res.data;
                        }
                    });
                    //获取投稿详情
                    if (id > 0) {
                        await AxiosAjax({
                            url: `/client/article/contribute/${id}`,
                            loading: false,
                            success: function (res) {
                                //赋值给model
                                Object.keys(_this.model).forEach(key => {
                                    _this.model[key] = res.data[key];
                                });
                                _this.model.albums = JSON.parse(_this.model.albumMeta);
                                _this.model.attachs = JSON.parse(_this.model.attachMeta);
                                console.log(_this.model.fields);
                                //赋值扩展字段
                                _this.status = _this.model.status;
                                //相册赋值
                                if (_this.model.albums) {
                                    _this.model.albums.map(function (item) {
                                        item.url = item.thumbPath;
                                        item.id = 0;
                                        _this.form.albumList.push(item);
                                    })
                                }
                                //附件赋值
                                if (_this.model.attachs) {
                                    _this.model.attachs.map(function (item) {
                                        item.fileName = item.fileName;
                                        item.articleId = item.articleId;
                                        item.filePath = item.filePath;
                                        item.fileSize = item.fileSize;
                                        item.fileExt = item.fileExt;
                                        item.downCount = item.downCount;
                                        item.id = 0;
                                        _this.form.attachList.push(item);
                                    })
                                }

                                _this.getChannelModel(_this.model.channelId);


                            }
                        });
                    };
                    //获取频道列表
                    await AxiosAjax({
                        url: `/client/channel/view/0`,
                        success: function (res) {
                            _this.channelList = [];
                            res.data.forEach((item, index, array) => {
                                if (item.isContribute == 1 && item.status==0) {
                                    _this.channelList.push(item);
                                }
                            })
                            //console.log(_this.channelList);
                        }
                    });
                },
                //频道变化
                handleChannelChange(val) {
                    let _this = this;
                    _this.getChannelModel(val);
                },
                //获得频道信息
                getChannelModel(channelId) {
                    let _this = this;

                    AxiosAjax({
                        url: `/client/channel/${channelId}`,
                        loading: false,
                        success: function (res) {
                            //debugger;
                            _this.channelModel = res.data;
                            _this.model.fields = _this.channelModel.fields;
                            //获得频道扩展字段
                            _this.initFields();

                        }
                    });
                },
                ////初始化扩展字段
                //initFields() {
                //    let _this = this;
                //    //重置验证规则
                //    _this.fieldRules = {};
                //    //重置表单
                //    _this.channelModel.fields.forEach(function (val, i) {

                //        //编辑的时候触发
                //        if (_this.model.id > 0) {
                //            //获得扩展字段值
                //            let obj = getFieldsValue(val.name);
                //            //构建Fields属性
                //            val.fieldName = val.name;
                //            val.fieldId = obj.id;
                //            //如果值存在，将值替换默认值
                //            if (obj.value) {
                //                //如果是数组
                //                if (Array.isArray(val.fieldValue)) {
                //                    val.fieldValue = obj.value.split(',');
                //                } else {
                //                    val.fieldValue = obj.value;
                //                }

                //            } else {
                //                if (Array.isArray(val.fieldValue)) {
                //                    val.fieldValue = [];
                //                } else {
                //                    val.fieldValue = '';
                //                }

                //            }
                //        } else {
                //            //构建Fields属性
                //            val.fieldName = val.name;
                //            val.fieldId = val.id;
                //        }
                //        //生成验证规则
                //        getRules(val);
                //    });
                //    _this.model.fields = _this.channelModel.fields;
                //    //获得扩展字段值
                //    function getFieldsValue(name) {
                //        let obj = { value: '', id: 0 };
                //        let fields= JSON.parse(_this.model.fieldMeta)
                //        if (fields.length > 0) {
                //            fields.forEach(function (val, index) {
                //                if (val.fieldName == name) {
                //                    obj = { value: val.fieldValue, id: val.fieldId };
                //                }
                //            });
                //        }
                //        return obj;
                //    }
                //    //生成验证规则
                //    function getRules(obj) {
                //        let item = [];
                //        //blur验证的控件
                //        if (obj.controlType == 'input' ||
                //            obj.controlType == 'textarea' ||
                //            obj.controlType == 'editor' ||
                //            obj.controlType == 'images' ||
                //            obj.controlType == 'video' ||
                //            obj.controlType == 'datetime'
                //        ) {
                //            //必填项
                //            if (obj.isRequired == 1) {
                //                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'blur' };
                //                item.push(eleRule);
                //            }
                //            //检查正则是否为null
                //            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                //                //不为空，将字符串转成正则表达式
                //                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'blur' }
                //                item.push(eleRule);
                //            }

                //        } else if (obj.controlType == 'radio' ||
                //            obj.controlType == 'checkbox') {
                //            //change验证的控件
                //            //必填项
                //            if (obj.isRequired == 1) {
                //                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'change' };
                //                item.push(eleRule);
                //            }
                //            //检查正则是否为null
                //            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                //                //不为空，将字符串转成正则表达式
                //                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'change' }
                //                item.push(eleRule);
                //            }
                //        }
                //        let name = obj.name;
                //        _this.fieldRules[name] = item;
                //    };
                //    console.log("验证了哦");
                //    console.log(_this.fieldRules);
                //},
                //初始化扩展字段
                initFields() {
                    let _this = this;
                    //重置验证规则
                    _this.fieldRules = {};
                    //重置表单
                    _this.channelModel.fields.forEach(function (val, i) {
                        //编辑的时候触发
                        if (_this.model.id > 0) {
                            //获得扩展字段值
                            let obj = getFieldsValue(val.name);
                            //构建Fields属性
                            val.fieldName = val.name;
                            val.fieldId = obj.id;
                            //如果值存在，将值替换默认值
                            if (obj.value) {
                                //如果是数组
                                if (Array.isArray(val.fieldValue)) {
                                    val.fieldValue = obj.value.split(',');
                                } else {
                                    val.fieldValue = obj.value;
                                }

                            } else {
                                if (Array.isArray(val.fieldValue)) {
                                    val.fieldValue = [];
                                } else {
                                    val.fieldValue = '';
                                }

                            }
                        } else {
                            //构建Fields属性
                            val.fieldName = val.name;
                            val.fieldId = val.id;
                        }
                        //生成验证规则
                        getRules(val);
                    });
                    _this.model.fields = _this.channelModel.fields;
                    //获得扩展字段值
                    //function getFieldsValue(name) {
                    //    let obj = { value: '', id: 0 };
                    //    if (_this.model.fields.length > 0) {
                    //        _this.model.fields.forEach(function (val, index) {
                    //            if (val.fieldName == name) {
                    //                obj = { value: val.fieldValue, id: val.fieldId };
                    //            }
                    //        });
                    //    }
                    //    return obj;
                    //}
                    function getFieldsValue(name) {
                        let obj = { value: '', id: 0 };
                        let fields = JSON.parse(_this.model.fieldMeta)
                        if (fields.length > 0) {
                            fields.forEach(function (val, index) {
                                if (val.fieldName == name) {
                                    obj = { value: val.fieldValue, id: val.fieldId };
                                }
                            });
                        }
                        return obj;
                    }
                    //生成验证规则
                    function getRules(obj) {
                        let item = [];
                        //blur验证的控件
                        if (obj.controlType == 'input' ||
                            obj.controlType == 'textarea' ||
                            obj.controlType == 'editor' ||
                            obj.controlType == 'images' ||
                            obj.controlType == 'video' ||
                            obj.controlType == 'datetime'
                        ) {
                            //必填项
                            if (obj.isRequired == 1) {
                                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'blur' };
                                item.push(eleRule);
                            }
                            //检查正则是否为null
                            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                                //不为空，将字符串转成正则表达式
                                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'blur' }
                                item.push(eleRule);
                            }

                        } else if (obj.controlType == 'radio' ||
                            obj.controlType == 'checkbox') {
                            //change验证的控件
                            //必填项
                            if (obj.isRequired == 1) {
                                let eleRule = { required: true, message: obj.title + '不能为空', trigger: 'change' };
                                item.push(eleRule);
                            }
                            //检查正则是否为null
                            if (!(!obj.validPattern && typeof (obj.validPattern) != 'undefined' && obj.validPattern != 0)) {
                                //不为空，将字符串转成正则表达式
                                let eleRule = { pattern: eval(obj.validPattern), message: obj.validErrorMsg, trigger: 'change' }
                                item.push(eleRule);
                            }
                        }
                        let name = obj.name;
                        _this.fieldRules[name] = item;
                    };
                },
                //提交表单
                submitForm() {
                    let _this = this; //当前页面

                    //多个表单验证
                    const f1 = new Promise((resolve, reject) => {
                        _this.$refs['editForm'].validate((valid) => {
                            if (valid) resolve()
                        });
                    });
                    Promise.all([f1]).then(() => {
                        console.log(_this.model);
                        let model = JSON.parse(JSON.stringify(_this.model));
                        console.log(model);
                        //处理扩展字段
                        model.fields.forEach(function (val, index) {
                            if (Array.isArray(val.fieldValue)) {
                                val.fieldValue = val.fieldValue.join(',');
                            }
                        });
                        //格式化相册数据去除没有上传成功的数据
                        _this.formatAlbum();
                        //格式化附件数据去除没有上传成功的数据
                        _this.formatAttach();
                        //相册取值
                        let albumList = [];
                        _this.form.albumList.map(function (item) {
                            albumList.push({
                                id: 0,
                                articleId: 0,
                                thumbPath: item.thumbPath,
                                originalPath: item.originalPath,
                                remark: item.remark
                            });
                        });
                        model.albums = albumList;
                        //附件取值
                        let attachList = [];
                        _this.form.attachList.map(function (item) {

                            attachList.push({
                                id: 0,
                                fileName: item.fileName,
                                articleId: 0,
                                filePath: item.filePath,
                                fileSize: item.fileSize,
                                fileExt: item.fileExt,
                                downCount: item.downCount,
                            });
                        });
                        model.attachs = attachList;
                        //提交表单,Id大于0则修改，否则添加
                        if (_this.model.id > 0) {
                            AxiosAjax({
                                method: 'put',
                                url: `/client/article/contribute/${_this.model.id}`,
                                data: model,
                                loading: true,
                                successMsg: '修改成功',
                                success: function (res) {
                                    //可跳转加列表页
                                    common.linkUrl("/account/contribute/list");
                                }
                            });
                        } else {
                            AxiosAjax({
                                method: 'post',
                                url: `/client/article/contribute`,
                                data: model,
                                loading: true,
                                successMsg: '新增成功',
                                success: function (res) {
                                    //重置表单
                                    _this.$refs['editForm'].resetFields();
                                    _this.form.albumList = [];
                                    _this.form.attachList = [];
                                    _this.model.albums = [];
                                    _this.model.attachs = [];
                                    _this.model.albumMeta = '';
                                    _this.model.attachMeta = '';
                                    _this.model.fieldMeta = '';
                                    /*_this.model.fields = [];*/
                                    //_this.linkUrl(`/article/contributelist`);
                                }
                            });
                        }
                    })
                },
                //格式化相册数据
                formatAlbum() {
                    let _this = this;
                    let albumsArr = [];
                    if (_this.model.albums) {
                        let albums = _this.model.albums;
                        for (let i = 0; i < albums.length; i++) {
                            if (albums[i].status === 'success') {
                                albumsArr.push(albums[i]);
                            }
                        }
                        _this.model.albums = albumsArr;
                    }
                },
                //格式化附件数据
                formatAttach() {
                    let _this = this;
                    let attachArr = [];
                    if (_this.model.attachs) {
                        let attachs = _this.model.attachs;
                        for (let i = 0; i < attachs.length; i++) {
                            if (attachs[i].status === 'success') {
                                attachArr.push(attachs[i]);
                            }
                        }
                        _this.model.attachs = attachArr;
                    }
                },
            },
            mounted: function () {
                //初始化数据
                this.initData(@Model);
            },
            created() {
                //this.initData(@Model)
            }
        })
    </script>
}